package com.bardsoftware.foronuvolo.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;

public class AnswersViewUI implements EntryPoint {
    private final AddCommentServiceAsync myAddCommentService = GWT.create(AddCommentService.class);
    private MessageSender myMessageSender;

    public void onModuleLoad() {
        String url = Document.get().getURL();
        int pathPrefix = url.lastIndexOf(ForoNuvoloConstants.ANSWERS_VIEW_PATH);
        int lastHash = url.lastIndexOf('#');
        if (pathPrefix == -1 || lastHash == -1 || lastHash <= pathPrefix) {
            return;
        }
        final String discussionRefID = Urls.getDiscussionRefIDFromViewPath(url.substring(pathPrefix, lastHash));
        GWT.log("refid="+discussionRefID, null);
        RootPanel sendButtonsRoot = RootPanel.get("send_button");
		myMessageSender = new AnswerMessageSender(
                RootPanel.get("new_comment"),
                sendButtonsRoot,
                new MessageSendService() {
                    public void sendMessage(String message, AsyncCallback<String> callback) {
                        myAddCommentService.addComment(discussionRefID, message, callback);
                    }
                },
                "new_comment_output",
                "new_comment_output") {
            protected void onSuccess(String result) {
                Element outputElement = Document.get().getElementById("new_comment_output");
                Element clone = (Element) outputElement.cloneNode(true);
                clone.setInnerHTML(result);
                clone.setId("");
                outputElement.getParentElement().insertBefore(clone, outputElement);
                getMessageField().setText("");
                getSendButton().setEnabled(true);
            }
            protected void onFailure(Throwable caught) {
                showErrorNotifier("err_notifier");
            }
        };
    }
}
